package com.flyco.modules.stm.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.util.DateUtils;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.pms.vo.PmsProductSkuVO;
import com.flyco.modules.stm.entity.StmSkuMaterial;
import com.flyco.modules.stm.service.IStmSkuMaterialService;

import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: SKU与物料关联表
 * @Author: flyco
 * @Date:   2020-11-18
 * @Version: V1.0
 */
@Slf4j
@Api(tags="SKU与物料关联表")
@RestController
@RequestMapping("/f/stm/stmSkuMaterial")
public class StmSkuMaterialController extends BaseController<StmSkuMaterial, IStmSkuMaterialService> {
	@Autowired
	private IStmSkuMaterialService stmSkuMaterialService;
	 @Autowired
	 private IPmsProductService pmsProductService;
	
	/**
	 * 分页列表查询
	 *
	 * @param stmSkuMaterial
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "SKU与物料关联表-分页列表查询")
	@ApiOperation(value="SKU与物料关联表-分页列表查询", notes="SKU与物料关联表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StmSkuMaterial stmSkuMaterial,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<StmSkuMaterial> queryWrapper = QueryGenerator.initQueryWrapper(stmSkuMaterial, req.getParameterMap());
		Page<StmSkuMaterial> page = new Page<StmSkuMaterial>(pageNo, pageSize);
		IPage<StmSkuMaterial> pageList = stmSkuMaterialService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 * 添加
	 *
	 * @param stmSkuMaterial
	 * @return
	 */
	@AutoLog(value = "SKU与物料关联表-添加")
	@ApiOperation(value="SKU与物料关联表-添加", notes="SKU与物料关联表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody StmSkuMaterial stmSkuMaterial) {
		LambdaQueryWrapper<PmsProduct> query = new LambdaQueryWrapper<PmsProduct>();
		query.eq(PmsProduct::getProductSn,stmSkuMaterial.getProductSn());
		PmsProduct product = pmsProductService.getOne(query,false);
		if (oConvertUtils.isEmpty(product)) return Result.error("该货号不存在，请检查后再试！");
		stmSkuMaterial.setProductId(product.getId());
		/*stmSkuMaterial.setDefFlag(1);
		LambdaQueryWrapper<StmSkuMaterial> materialQuery = new LambdaQueryWrapper<StmSkuMaterial>();
		materialQuery.eq(StmSkuMaterial::getProductId,product.getId());
		materialQuery.eq(StmSkuMaterial::getProductSn,stmSkuMaterial.getProductSn());
		materialQuery.eq(StmSkuMaterial::getSkuCode,stmSkuMaterial.getSkuCode());
		if (stmSkuMaterialService.count(materialQuery) > 0) {
			StmSkuMaterial updateMaterial = new StmSkuMaterial();
			updateMaterial.setDefFlag(0);
			stmSkuMaterialService.update(updateMaterial,materialQuery);
		}*/
		stmSkuMaterialService.save(stmSkuMaterial);
		return Result.ok("添加成功！");
	}
	
	/**
	 * 编辑
	 *
	 * @param stmSkuMaterial
	 * @return
	 */
	@AutoLog(value = "SKU与物料关联表-编辑")
	@ApiOperation(value="SKU与物料关联表-编辑", notes="SKU与物料关联表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody StmSkuMaterial stmSkuMaterial) {
		/*StmSkuMaterial dbSkuMaterial = stmSkuMaterialService.getById(stmSkuMaterial.getId());
		LambdaQueryWrapper<StmSkuMaterial> materialQuery = new LambdaQueryWrapper<StmSkuMaterial>();
		materialQuery.eq(StmSkuMaterial::getProductId,dbSkuMaterial.getProductId());
		materialQuery.eq(StmSkuMaterial::getProductSn,dbSkuMaterial.getProductSn());
		materialQuery.eq(StmSkuMaterial::getSkuCode,dbSkuMaterial.getSkuCode());
		materialQuery.ne(StmSkuMaterial::getId,stmSkuMaterial.getId());
		if (1 == stmSkuMaterial.getDefFlag()) {
			if (stmSkuMaterialService.count(materialQuery) > 0) {
				StmSkuMaterial updateMaterial = new StmSkuMaterial();
				updateMaterial.setDefFlag(0);
				stmSkuMaterialService.update(updateMaterial,materialQuery);
			}
		} else {
			materialQuery.eq(StmSkuMaterial::getDefFlag,1);
			if (stmSkuMaterialService.count(materialQuery) == 0) {
				return Result.error("同样的货号与SKU编码必须指定一个默认!");
			}
		}*/
		stmSkuMaterialService.updateById(stmSkuMaterial);
		return Result.ok("编辑成功!");
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "SKU与物料关联表-通过id删除")
	@ApiOperation(value="SKU与物料关联表-通过id删除", notes="SKU与物料关联表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		stmSkuMaterialService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "SKU与物料关联表-批量删除")
	@ApiOperation(value="SKU与物料关联表-批量删除", notes="SKU与物料关联表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.stmSkuMaterialService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "SKU与物料关联表-通过id查询")
	@ApiOperation(value="SKU与物料关联表-通过id查询", notes="SKU与物料关联表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		StmSkuMaterial stmSkuMaterial = stmSkuMaterialService.getById(id);
		return Result.ok(stmSkuMaterial);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param stmSkuMaterial
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, StmSkuMaterial stmSkuMaterial) {
      return super.exportXls(request, stmSkuMaterial, StmSkuMaterial.class, "SKU与物料关联表");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      //return super.importExcel(request, response, StmSkuMaterial.class);

	  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	  Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	  for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		  MultipartFile file = entity.getValue();// 获取上传文件对象
		  ImportParams params = new ImportParams();
		  params.setTitleRows(2);
		  params.setHeadRows(1);
		  params.setNeedSave(true);
		  try {
			  List<StmSkuMaterial> list = ExcelImportUtil.importExcel(file.getInputStream(), StmSkuMaterial.class, params);
			  //update-begin-author:taoyan date:20190528 for:批量插入数据

			  List<PmsProductSkuVO> productSkuVOS = pmsProductService.getProductSkuList();
			  Map<String,PmsProductSkuVO> productSnMap =  productSkuVOS.stream().collect(Collectors.toMap(PmsProductSkuVO::getProductSn, t -> t));

			  List<StmSkuMaterial> noSkus = new ArrayList<>();
			  list.forEach(m->{
				if (productSnMap.containsKey(m.getProductSn())) {
					m.setProductId(productSnMap.get(m.getProductSn()).getId());
					m.setSkuCode(productSnMap.get(m.getProductSn()).getSkuCode());
					if (oConvertUtils.isEmpty(m.getStartTime())) {
						m.setStartTime(DateUtils.beginOfDay(DateUtils.getDate()));
					}
				} else {
					noSkus.add(m);
				}
			  });
			  list.removeAll(noSkus);
			  long start = System.currentTimeMillis();
			  stmSkuMaterialService.saveBatch(list);
			  //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
			  //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
			  log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
			  //update-end-author:taoyan date:20190528 for:批量插入数据

			  String msg = "成功导入：" + list.size() + "条";
			  if (noSkus.size() > 0) {
				  msg += "失败记录：";
				  msg += noSkus.stream().map(StmSkuMaterial::getProductSn).collect(Collectors.toList()).toString();
			  }
			  return Result.ok( msg );
		  } catch (Exception e) {
			  log.error(e.getMessage(), e);
			  return Result.error("文件导入失败:" + e.getMessage());
		  } finally {
			  try {
				  file.getInputStream().close();
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
	  }
	  return Result.error("文件导入失败！");
  }

}
